package fi.laurea.jsonbus;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;

public class Receiver {

	private String exhangeName = null;
	private Connection connection = null;
	private Channel channel = null;
	private String queueName;
	private QueueingConsumer consumer;

	public Receiver(String exhangeName, final String listenerId,
			final ReceiverListener listener) {
		this.exhangeName = exhangeName;
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("109.75.176.134");
		try {
			this.connection = factory.newConnection();
			this.channel = connection.createChannel();
			this.channel.exchangeDeclare(this.exhangeName, "topic");
			this.queueName = channel.queueDeclare().getQueue();
			channel.queueBind(queueName, this.exhangeName, "all");
			channel.queueBind(queueName, this.exhangeName, listenerId);
			this.consumer = new QueueingConsumer(channel);
			channel.basicConsume(this.queueName, true, consumer);
		} catch (IOException e) {
			e.printStackTrace();
		}

		new Thread(new Runnable() {
			public void run() {
				while (true) {
					QueueingConsumer.Delivery delivery = null;
					try {
						delivery = consumer.nextDelivery();

					} catch (ShutdownSignalException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ConsumerCancelledException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					String message = new String(delivery.getBody());
					String routingKey = delivery.getEnvelope().getRoutingKey();
					if (routingKey.equals("all")) {
						listener.prosessGloballMessage(message);
					}
					if (routingKey.equals(listenerId)) {
						listener.prosessPrivateMessage(message);
					}
				}
			}
		}).start();
	}
}
